package com.tanhua.api.impl.mongo;

import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class FriendsApiImpl implements FriendsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void contacts(Integer userId, Long id) {

        Friend friend1 = new Friend();
        friend1.setCreated(System.currentTimeMillis());
        friend1.setUserId(userId.longValue());
        friend1.setFriendId(id);
        mongoTemplate.insert(friend1);


        Friend friend2 = new Friend();
        friend2.setCreated(System.currentTimeMillis());
        friend2.setUserId(id);
        friend2.setFriendId(userId.longValue());
        mongoTemplate.insert(friend2);
    }

    @Override
    public PageBeanVo findFriendsList(Integer page, Integer pagesize,Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        return new PageBeanVo(page,pagesize,count,friendList);
    }

    @Override
    public List<Long> findFriendsId(Long userId) {

        Query query = new Query(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        List<Long> friendIdList=new ArrayList<>();
        if (friendList!=null){
        for (Friend friend : friendList) {
           friendIdList.add(friend.getFriendId());
        }
        }
        return friendIdList;
    }

    @Override
    public long findeachLoveCount(Long id) {

        Query query = new Query(Criteria.where("userId").is(id));
        long count = mongoTemplate.count(query, Friend.class);
        return count;
    }

    @Override
    public void deleteFriends(Long userid, Integer uid) {

        Query query1 = new Query(Criteria.where("userId").is(userid).and("friendId").is(uid));
        mongoTemplate.remove(query1,"tanhua_friends");


        Query query2 = new Query(Criteria.where("userId").is(uid).and("friendId").is(userid));
        mongoTemplate.remove(query2,"tanhua_friends");


    }

    @Override
    public Boolean isFriends(Integer uid, Long userid) {
        Query query = new Query(Criteria.where("userId").is(userid).and("friendId").is(uid));
        long count = mongoTemplate.count(query, "tanhua_friends");
        return count>0?true:false; //三元运算
    }
}
